package cn.huyanbing.middleware.thread.research;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @BelongProject middleware
 * @BelongPackage cn.huyanbing.middleware.thread.research
 * @Description TODO
 * @ClassName RateLimiter
 * @Author huyangbing
 * @Date 2024/11/21 23:29
 * @Version 1.0.0
 */
public class RateLimiterTest {

    private static long prev =0L;

    public static void main(String[] args) {
        RateLimiter limiter = RateLimiter.create(2.0);

        //执行任务的线程池
        ExecutorService es = Executors.newFixedThreadPool(1);
        //记录上一次执行时间
        prev = System.nanoTime();
        //测试执行20次

        for (int i = 0; i < 20; i++) {
            //限流器限流
            limiter.acquire();

            //提交任务异步执行
            es.execute(() -> {

                long cur = System.nanoTime();
                //打印时间间隔:毫秒
                System.out.println((cur - prev) / 1000_000);

                prev = cur;
            });
        }
    }
}
